<% layout('/layouts/default.html', {title: '应付单管理', libs: ['validate','dataGrid']}){ %>
<div class="main-content">
	<div class="box box-main">
		<div class="box-header with-border">
			<div class="box-title">
				<i class="fa icon-note"></i> ${text(tap.isNewRecord ? '新增应付单' : '编辑应付单')}

			</div>
			<div class="box-tools pull-right">
				<button type="button" class="btn btn-box-tool" data-widget="collapse"><i class="fa fa-minus"></i></button>
			</div>
		</div>
		<#form:form id="inputForm" model="${tap}" action="${ctx}/payment/tap/save" method="post" class="form-horizontal">
			<div class="box-body">
				<div class="form-unit">${text('基本信息')}</div>
				<#form:hidden path="apId"/>
				<div class="row">
					<div class="col-xs-6">
						<div class="form-group">
							<label class="control-label col-sm-4" title="">
								<span class="required hide">*</span> ${text('编号')}：<i class="fa icon-question hide"></i></label>
							<div class="col-sm-8">
								<#form:input path="serviceOrderCode" maxlength="100" class="form-control" placeholder="自动生成" readonly="true"/>
							</div>
						</div>
					</div>
					<div class="col-xs-6">
						<div class="form-group">
							<label class="control-label col-sm-4" title="">
								<span class="required ">*</span> ${text('供应商')}：<i class="fa icon-question hide"></i></label>
							<div class="col-sm-8">
								<#form:select path="supplierId" items="${supplierList}" itemLabel="supplierName" itemValue="supplierId"
								class="form-control required" blankOption="true"  onchange="getByCuId()"/>

							</div>
						</div>
					</div>
					<div class="col-xs-6">
						<div class="form-group">
							<label class="control-label col-sm-4" title="">
								<span class="required ">*</span> ${text('日期')}：<i class="fa icon-question hide"></i></label>
							<div class="col-sm-8">
								<#form:input path="date" readonly="true" maxlength="20" class="form-control laydate required"
									dataFormat="date" data-type="date" data-format="yyyy-MM-dd"/>
							</div>
						</div>
					</div>

					<div class="col-xs-6">
						<div class="form-group">
							<label class="control-label col-sm-4" title="">
								<span class="required ">*</span> ${text('服务订单')}：<i class="fa icon-question hide"></i></label>
							<div class="col-sm-8">
								<#form:select path="serviceOrderId" items="${serviceOrderList}" itemLabel="serviceOrderCode" itemValue="serviceOrderId"
								class="form-control required" blankOption="true" onchange="getFrameNumber()"/>
							</div>
						</div>
					</div>
					<div class="col-xs-6">
						<div class="form-group">
							<label class="control-label col-sm-4" title="">
								<span class="required hide">*</span> ${text('付款账号')}：<i class="fa icon-question hide"></i></label>
							<div class="col-sm-8">
								<#form:input path="paymentAccount" maxlength="100" class="form-control" />
							</div>
						</div>
					</div>
					<div class="col-xs-6">
						<div class="form-group">
							<label class="control-label col-sm-4" title="">
								<span class="required hide">*</span> ${text('金额')}：<i class="fa icon-question hide"></i></label>
							<div class="col-sm-8">
								<#form:input path="amount" maxlength="100" class="form-control" readonly="true"/>
							</div>
						</div>
					</div>
					<div class="col-xs-6">
						<div class="form-group">
							<label class="control-label col-sm-4" title="">
								<span class="required hide">*</span> ${text('币种')}：<i class="fa icon-question hide"></i></label>
							<div class="col-sm-8">
								<#form:select path="currency" dictType="sys_bizhongy" class="form-control" blankOption="false"/>
							</div>
						</div>
					</div>
					<div class="col-xs-6">
						<div class="form-group">
							<label class="control-label col-sm-4" title="">
								<span class="required hide">*</span> ${text('前置单据类型')}：<i class="fa icon-question hide"></i></label>
							<div class="col-sm-8">
								<#form:select path="parentBillType" dictType="erp_record_type" blankOption="true" class="form-control" readonly="true"/>
							</div>
						</div>
					</div>
					<div class="col-xs-6">
						<div class="form-group">
							<label class="control-label col-sm-4" title="">
								<span class="required hide">*</span> ${text('前置单据编号')}：<i class="fa icon-question hide"></i></label>
							<div class="col-sm-8">
								<#form:select path="parentBillCode" dictType="" blankOption="true" class="form-control" readonly="true"/>
							</div>
						</div>
					</div>
				</div>
				<div class="row">
					<div class="col-xs-12">
						<div class="form-group">
							<label class="control-label col-sm-2" title="">
								<span class="required hide">*</span> ${text('备注信息')}：<i class="fa icon-question hide"></i></label>
							<div class="col-sm-10">
								<#form:textarea path="remarks" rows="4" maxlength="500" class="form-control"/>
							</div>
						</div>
					</div>
				</div>
				<h4 class="form-unit">${text('应付单明细')}</h4>
				<div class="ml10 mr10">
					<table id="tapDetailDataGrid"></table>
					<% if (hasPermi('payment:tap:edit')){ %>
						<a href="#" id="tapDetailDataGridAddRowBtn" class="btn btn-primary btn-sm mt10 mb10"><i class="fa fa-plus"></i> ${text('增行')}</a>
					<% } %>
				</div>
			</div>
		<div class="form-unit">${text('系统信息')}</div>
		<div class="row">
			<div class="col-xs-6">
				<div class="form-group">
					<label class="control-label col-sm-4" title="">
						<span class="required hide">*</span> ${text('创建者')}：<i class="fa icon-question hide"></i></label>
					<div class="col-sm-8">
						<#form:input path="createBy" maxlength="64" class="form-control " readonly="true"/>
					</div>
				</div>
			</div>
			<div class="col-xs-6">
				<div class="form-group">
					<label class="control-label col-sm-4" title="">
						<span class="required hide">*</span> ${text('创建时间')}：<i class="fa icon-question hide"></i></label>
					<div class="col-sm-8">
						<#form:input path="createDate" readonly="true" maxlength="20" class="form-control "
						dataFormat="date" data-type="date" data-format="yyyy-MM-dd"/>
					</div>
				</div>
			</div>
			<div class="col-xs-6">
				<div class="form-group">
					<label class="control-label col-sm-4" title="">
						<span class="required hide">*</span> ${text('更新者')}：<i class="fa icon-question hide"></i></label>
					<div class="col-sm-8">
						<#form:input path="updateBy" maxlength="64" class="form-control " readonly="true"/>
					</div>
				</div>
			</div>
			<div class="col-xs-6">
				<div class="form-group">
					<label class="control-label col-sm-4" title="">
						<span class="required hide">*</span> ${text('更新时间')}：<i class="fa icon-question hide"></i></label>
					<div class="col-sm-8">
						<#form:input path="updateDate" class="form-control " readonly="true"
						dataFormat="date" data-type="date" data-format="yyyy-MM-dd"/>
					</div>
				</div>
			</div>
		</div>
			<div class="box-footer">
				<div class="row">
					<div class="col-sm-offset-2 col-sm-10">
						<% if (hasPermi('payment:tap:edit')){ %>
							<button type="submit" class="btn btn-sm btn-primary" id="btnSubmit"><i class="fa fa-check"></i> ${text('保 存')}</button>&nbsp;
						<% } %>
						<button type="button" class="btn btn-sm btn-default" id="btnCancel" onclick="js.closeCurrentTabPage()"><i class="fa fa-reply-all"></i> ${text('关 闭')}</button>
					</div>
				</div>
			</div>
		</#form:form>
	</div>
</div>
<% } %>
<script>
//初始化应付单明细DataGrid对象
$("#tapDetailDataGrid").dataGrid({
	// var list = getFrameNumber(),
	data: ${toJson(tap.tapDetailList)},
	datatype: "local", // 设置本地数据
	autoGridHeight: function(){return 'auto'}, // 设置自动高度
	
	// 设置数据表格列
	columnModel: [
		{header:'状态', name:'status', editable:true, hidden:true},
		{header:'主键', name:'apDetailId', editable:true, hidden:true},
		{header:'${text("行号")}', name:'rowNumber',width:190,
			editable:true, edittype:'select',  editoptions: {
					'class': 'form-control required',
					items: ${toJson(rowNumberList)},
					itemLabel: 'rowNumber', itemValue: 'rowNumber',
					dataInit: function (element) {
						$(element).select2().on("change", function () {
							if ($(this).val() == "") {

								$(this).closest('tr').find('[aria-describedby="tapDetailDataGrid_frameNumber"] .form-control').val("").trigger('change');
								$(this).closest('tr').find('[aria-describedby="tapDetailDataGrid_brand"] .form-control').val("").trigger('change');
								$(this).closest('tr').find('[aria-describedby="tapDetailDataGrid_area"] .form-control').val("").trigger('change');
								$(this).closest('tr').find('[aria-describedby="tapDetailDataGrid_model"] .form-control').val("").trigger('change');
								$(this).closest('tr').find('[aria-describedby="tapDetailDataGrid_carId"] .form-control').val("").trigger('change');
								return;
							}
							//订单号
							var serviceOrderId = $("#serviceOrderId").val();
							let car = {};
							$(this).resetValid();
							$.ajax({
								type: "POST",
								async: false,
								url: "${ctx}/payment/tap/getCarDetailInfo1",
								data: {"rowNumber": $(this).val(), "serviceOrderId": serviceOrderId},
								success: function (data) {
									car.area = data.area;
									car.brand = data.brand;
									car.model = data.model;
									car.carId = data.carId;
									car.frameNumber = data.frameNumber;
								}
							});
							$(this).closest('tr').find('[aria-describedby="tapDetailDataGrid_frameNumber"] .form-control').val(car.frameNumber).trigger('change');
							$(this).closest('tr').find('[aria-describedby="tapDetailDataGrid_brand"] .form-control').val(car.brand).trigger('change');
							$(this).closest('tr').find('[aria-describedby="tapDetailDataGrid_area"] .form-control').val(car.area).trigger('change');
							$(this).closest('tr').find('[aria-describedby="tapDetailDataGrid_model"] .form-control').val(car.model).trigger('change');
							$(this).closest('tr').find('[aria-describedby="tapDetailDataGrid_carId"] .form-control').val(car.carId).trigger('change');
						});
					}
				}
		},
		{header:'车架号', name:'frameNumber', editable:true,edittype:'text',hidden:false,editoptions:{'class':'form-control','readonly':'true'}},
		{header:'${text("品牌")}', name:'brand', width:150, editable:true, edittype:'select', editoptions:{'maxlength':'2', 'class':'form-control required','readonly':'true',
				items: $.merge([{dictLabel:'&nbsp;',dictValue:''}], ${@DictUtils.getDictListJson('car_pinpai')}),
				itemLabel: 'dictLabel', itemValue: 'dictValue'
			}},
		{header:'${text("版型")}', name:'area', width:150, editable:true, edittype:'select', editoptions:{'maxlength':'64', 'class':'form-control required','readonly':'true',
				items: $.merge([{dictLabel:'&nbsp;',dictValue:''}], ${@DictUtils.getDictListJson('car_quyu')}),
				itemLabel: 'dictLabel', itemValue: 'dictValue'
			}},
		{header:'${text("车型")}', name:'model', width:150, editable:true, edittype:'text', editoptions:{'maxlength':'100', 'class':'form-control required','readonly':'true'}},
		{header:'${text("车辆")}', name:'carId', width:150, editable:true, edittype:'text', editoptions:{'maxlength':'64', 'class':'form-control required','readonly':'true'}},
		{header:'${text("费用项目")}', name:'expenseItem', width:150,
			editable:true, edittype:'select', editoptions:{'class':'form-control required',
				    dataInit: function(element){
					$(element).select2().on("change",function(){});
				}
			}
		},
		{header:'${text("应付金额")}', name:'apAmount', width:150, editable:true, edittype:'text', editoptions:{'class':'form-control required number',
				dataInit: function(element) {
					$(element).change(function(){
						// 重新进行当前控件的表单验证
						$(this).resetValid();
						// 下拉框选择后，自动给指定列的输入框赋值（联动实例）
						let apAmount = $(this).closest('tr').find('[aria-describedby="tapDetailDataGrid_apAmount"] .form-control').val();
						let total = apAmount + $(this).val();
						$(this).find('[aria-describedby="amount"] .form-control').val(total);
					});
				}
		}},
		{header:'${text("实付金额")}', name:'actualApAmount', width:150, editable:true, edittype:'text', editoptions:{'class':'form-control number','readonly':'true'}},
		{header:'${text("备注")}', name:'remarik', width:150, editable:true, edittype:'text', editoptions:{'maxlength':'255', 'class':'form-control'}},
		{header:'${text("应付单ID")}', name:'apId.apId', editable:true, hidden:true},
		{header:'${text("操作")}', name:'actions', width:80, sortable:false, fixed:true, formatter: function(val, obj, row, act){
			var actions = [];
			if (val == 'new'){
				actions.push('<a href="#" onclick="js.confirm(\'${text("你确认要删除这条数据吗？")}\', function(){$(\'#tapDetailDataGrid\').dataGrid(\'delRowData\',\''+obj.rowId+'\')});return false;"><i class="fa fa-trash-o"></i></a>&nbsp;');
			}else{
				actions.push('<a href="#" onclick="js.confirm(\'${text("你确认要删除这条数据吗？")}\', function(){$(\'#tapDetailDataGrid\').dataGrid(\'setRowData\',\''+obj.rowId+'\',null,{display:\'none\'});$(\'#'+obj.rowId+'_status\').val(\''+Global.STATUS_DELETE+'\');});return false;"><i class="fa fa-trash-o"></i></a>&nbsp;');
			}
			return actions.join('');
		}, editoptions: {defaultValue: 'new'}}
	],
	
	// 编辑表格参数
	editGrid: true,				// 是否是编辑表格
	editGridInitRowNum: 1,		// 编辑表格的初始化新增行数
	editGridAddRowBtn: $('#tapDetailDataGridAddRowBtn'),	// 子表增行按钮
	editGridAddRowInitData: {apDetailId: '', status: Global.STATUS_NORMAL},	// 新增行的时候初始化的数据
	
	// 编辑表格的提交数据参数
	editGridInputFormListName: 'tapDetailList', // 提交的数据列表名
	editGridInputFormListAttrs: 'status,rowNumber,apDetailId,brand,area,model,carId,frameNumber,expenseItem,apAmount,actualApAmount,remarik,apId.apId,', // 提交数据列表的属性字段
	
	// 加载成功后执行事件
	ajaxSuccess: function(data){
		
	}
});
</script>
<script>
$("#inputForm").validate({
	submitHandler: function(form){
		js.ajaxSubmitForm($(form), function(data){
			js.showMessage(data.message);
			if(data.result == Global.TRUE){
				js.closeCurrentTabPage(function(contentWindow){
					contentWindow.page();
				});
			}
		}, "json");
    }
});

//原先为获得车架号，已改为获得行号
function getFrameNumber(){

	var str = ':;'
	if ($("#serviceOrderId").val() != "") {
		$.ajax({
			type: "POST",
			url: "${ctx}/payment/tap/getNumberList1",
			data: {
				"serviceOrderId": $("#serviceOrderId").val(),
			},
			success: function (data) {
				if (data!= "") {

					//根据订单编号赋值行号
					if (data.length > 0) {

						for (var i = 0; i < data.length; i++) {
							var number = data[i];

							if(i!=data.length-1){
								str+=number+":"+number+";";
							}else {
								str+=number+":"+number;// 这里是option里面的 value:label
							}
						}

					} else{
						js.showErrorMessage("该订单没有行号信息！");
					}
				} else{
					js.showErrorMessage("该订单没有行号信息！");
				}
				// alert(str);
				$('#tapDetailDataGrid').setColProp('rowNumber', {editoptions: {value:str,readOnly: true}});
				$('#tapDetailDataGrid').dataGrid('reloadGrid');
			}
		});
	} else {
		js.showErrorMessage("未选择订单！");
	}

}


//费用项目
$(function () {
	var str="";
	$.ajax({
		type: "POST",
		async : false,
		url: "${ctx}/payment/tap/getExpenseItem",
		// data: {"serviceOrderId": $("#serviceOrderId").val()},
		dataType : "json",
		success: function (data) {
			// $('#currency').select2('val', data.currency);
			//根据订单编号赋值车架号
			if (data.length > 0) {
				for (var i = 0; i < data.length; i++) {
					var frameNumber1 = data[i].fixedExpenseName;

					var frameNumberId = data[i].fixedExpenseId;
					if(i!=data.length-1){
						str+=frameNumberId+":"+frameNumber1+";";
					}else {
						str+=frameNumberId+":"+frameNumber1;// 这里是option里面的 value:label
					}
				}

			} else{
				js.showErrorMessage("该订单没有车架号信息！");
			}
			$('#tapDetailDataGrid').setColProp('expenseItem', {editoptions: {value:str}});
			$('#tapDetailDataGrid').dataGrid('reloadGrid');

		}
	});

})


$(function () {

	$("#date").attr("value",js.formatDate(new Date()
			, 'yyyy-MM-dd'));

	//鼠标失焦求和
	$("table[id='tapDetailDataGrid']").on("blur","input[name=\"apAmount\"]",function () {
		var money=0;
		$("input[name=\"apAmount\"]").each(function () {
			var text =/[0-9]*(\.[0-9]*)?/;
			var flag =text.test($(this).val());
			if(flag){
				if($(this).val()!=NaN&&$(this).val()!=null&&$(this).val()!=""){
					money=money+parseInt($(this).val());
				}
			}else{
				js.showErrorMessage("数据格式错误");
			}

		})
		$("input[id='amount']").val(money)
	})
})
//获取订单号
function getByCuId() {
	if ($("#customerId").val() != "") {
		$.ajax({
			type: "POST",
			async : false,
			url: "${ctx}/payment/tap/getTapBySuId",
			data: {"supplierId": $("#supplierId").val()},
			dataType : "json",
			success: function (data) {
				$("#serviceOrderId").empty();
				if (data.length > 0) {
					for (var i = 0; i < data.length; i++) {
						var orderId = data[i].serviceOrderId;
						var orderCode = data[i].serviceOrderCode;
						var option = $("<option>").attr({
							"value" : orderId
						}).text(orderCode);
						$("#serviceOrderId").append(option);
					}
					$("#serviceOrderId option:first").prop("selected", 'selected');
					$("#serviceOrderId").change();
				} else{
					js.showErrorMessage("该供应商没有订单信息！");
				}
			}
		});
	}
}

$(function () {
	if("!${tap.isNewRecord}"){
		$("#serviceOrderId").attr("readOnly",true)
		var list =$("#serviceOrderId").find("option")
		$(list[1]).prop("slected",true)
	}
})
</script>